#!/bin/bash
#name:fastapi-Blog启动脚本;
#date:2024-01-01;
#author：liming
#虚拟环境路径
APP_VENV='venv/bin/activate'
#程序路径
APP_PATH='/home/server/flask-imaotai'
#程序名称：
APP_NAME=app.py
#脚本菜单项
usage() {
 echo "Usage: sh runapi.sh [start|stop|restart|status]"
 exit 1
}

is_exist(){
 pid=`ps -ef|grep $APP_PATH/$APP_NAME|grep -v grep|awk '{print $2}' `
 #如果不存在返回1，存在返回0
 if [ -z "${pid}" ]; then
 return 1
 else
 return 0
 fi
}
#启动脚本
start(){
 is_exist
 if [ $? -eq "0" ]; then
 echo "${APP_NAME} is already running. Pid is ${pid}"
 else
#激活虚拟环境
source $APP_VENV
#此处注意修改程序路径和log文件文件位置,使用-u标志运行Python以避免输出缓冲
nohup python -u $APP_PATH/$APP_NAME > console.log 2>&1 &
#此处注意修改程序路径:不输出日志
# nohup python -u $APP_PATH/$APP_NAME &>/dev/null &
#此处打印log日志：
 #tail -f $APP_PATH/console.log
#查询一下运行状态
 status
 fi
}
#停止脚本
stop(){
 is_exist
 if [ $? -eq "0" ]; then
 kill -9 $pid
 echo "${APP_NAME} has been killed!"
 else
 echo "${APP_NAME} is not running."
 fi
}
#显示当前程序运行状态
status(){
 is_exist
 if [ $? -eq "0" ]; then
 echo "${APP_NAME} is running. Pid is ${pid}"
 else
 echo "${APP_NAME} is NOT running."
 fi
}
#重启脚本
restart(){
 stop
 start
}

case "$1" in
 "start")
 start
 ;;
 "stop")
 stop
 ;;
 "status")
 status
 ;;
 "restart")
 restart
 ;;
 *)
 usage
 ;;
esac
